import {useState , useEffect, useRef} from "react";
import {Link} from "react-router-dom";
import {Swiper, Divider, DotLoading} from "antd-mobile";
import HomeHead from "../components/HomeHead";
import _ from '@/assets/utils'
import './Home.less'
import api from "../api";
import SkeletonScreen from "../components/SkeletonScreen";
import NewsItem from "../components/NewsItem";

const Home = () => {

    let [timer , setTimer] = useState(_.formatTime(null,'{0}{1}{2}')),
        [banner , setBanner] = useState([]),
        [newsList, setNewsList] = useState([])

    // 第一次渲染请求数据，向服务器发布请求
    useEffect(() => {
       ( async () => {
            try {
                let {date , stories , top_stories} = await api.queryNewsLatest()
                setTimer(date)
                setBanner(top_stories)
                newsList.push({
                    date,
                    stories
                })
                setNewsList([...newsList])
            }catch (_) {}
        })()
    }, [])


    // 第一次数据渲染完毕，设置监听器，实现触底功能
    const loadMoreRef = useRef(null)
    useEffect(() => {
    // console.log(loadMoreRef.current);
      // 监听器对象
      let ob = new IntersectionObserver(async changes => {
        let { isIntersecting } = changes[0]
        if (isIntersecting) {
          // 触底了,加载过去的新闻
          const time = newsList[newsList.length - 1]['date']
          const res = await api.queryNewsBefore(time)
          newsList.push(res)
          setNewsList([...newsList])
        }
      })
      // 触发监听器
      ob.observe(loadMoreRef.current)

      // 因为组件销毁时，loadMoreRef.current会变成null，所有先用一个变量暂存它的值
      let loadBox = loadMoreRef.current
      // 在组建销毁释放时，销毁监听器
      return () => {
        ob.unobserve(loadBox)
        ob = null
      }
    }, [])

    return <div className='home-box'>
        {/*头部*/}
        <HomeHead timer={timer} />

        {/*轮播图*/}
        <div className={'swiper-box'}>
            <Swiper loop autoplay>
                {
                    banner.map(item => {
                       return <Swiper.Item key={item.id}>
                            <Link to={{pathname: `/detail/${item.id}`}}>
                                <img src={item.image} alt={item.image_hue}/>
                                <div className={'desc'}>
                                    <h3 className={'title'}>{item.title}</h3>
                                    <p className={"author"}>{item.hint}</p>
                                </div>
                            </Link>

                        </Swiper.Item>
                    })
                }


            </Swiper>
        </div>

        {/* 新闻列表 */}
      {newsList.length === 0 ? <SkeletonScreen /> :
        <>
          {newsList.map((item, index) => {
            let { date, stories } = item;
            return <div className="new-box" key={index}>
              {
                index !== 0 ? <Divider contentPosition="left" >{_.formatTime(date, '{1}月{2}日')} </Divider> : ''
              }
              <div className="list">
                {
                  stories.map(cur => {
                    return <NewsItem key={cur.id} info={cur} />
                  })
                }
              </div>
            </div>
          })}
        </>
      }

      <div 
        className="loadmore_box" 
        ref={loadMoreRef}
        style={{ display: newsList.length === 0 ? 'none' : 'block' }}
      >
        <DotLoading /> 数据加载中
      </div>
    </div>
}

export default Home
